package com.paishen.peiniwan.module;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.paishen.common.util.BaseUtil;
import com.paishen.common.widget.TitleLayout;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.Once;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.UpgradeService;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.UpgradeInfo;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.widget.PagerLayout;
import com.paishen.peiniwan.module.date.DateStartActivity;
import com.paishen.peiniwan.module.profile.MainProfileAuthLayout;
import com.paishen.peiniwan.module.profile.MainProfileBalanceChargeLayout;
import com.paishen.peiniwan.module.profile.MainProfileBalanceLayout;
import com.paishen.peiniwan.module.profile.MainProfileConcernLayout;
import com.paishen.peiniwan.module.profile.MainProfileDateLayout;
import com.paishen.peiniwan.module.profile.MainProfileFansLayout;
import com.paishen.peiniwan.module.profile.MainProfileLayout;
import com.paishen.peiniwan.module.profile.MainProfileSettingsLayout;
import com.paishen.peiniwan.module.profile.ProfileAlbumEditActivity;
import com.paishen.peiniwan.module.profile.ProfileInfoEditActivity;
import com.squareup.okhttp.Request;

import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity {
    private TitleLayout layTitle;

    private PagerLayout layPager;
    private MainLayout layMain;
    private MainProfileAuthLayout layMainProfileAuth;
    private MainProfileDateLayout layMainProfileDate;
    private MainProfileBalanceLayout layMainProfileBalance;
    private ViewGroup layOnce;

    private long clickBottomTimestamp, clickProfileTimestamp;

    private AlertDialog dlgUpgrade;
    private ProgressBar pbUpgrade;
    private TextView txUpgrade;
    private TextView txInstall;

    private AlertDialog dlgLocRetry;

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private ImageView makeImageTitle(int resid) {
        ImageView imgTitle = new ImageView(this);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.CENTER;
        imgTitle.setLayoutParams(lp);
        imgTitle.setImageResource(resid);
        return imgTitle;
    }

    @Override
    protected void onLocationPermissionOpened() {
        super.onLocationPermissionOpened();
        layMain.requestSquareIndex();
    }

    public void showLocRetryDialog() {
        // 检测是否包含定位权限
        int r1 = BaseUtil.checkOp(0); // AppOpsManager.OP_COARSE_LOCATION
        int r2 = BaseUtil.checkOp(1); // AppOpsManager.OP_FINE_LOCATION
        final boolean isNoPermission = r1 != 0 || r2 != 0;

        int message = isNoPermission ? com.paishen.libamap.R.string.location_retry_permission : com.paishen.libamap.R.string.location_retry_net;

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(com.paishen.libamap.R.string.location_fail).setMessage(message).setNegativeButton(com.paishen.libamap.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dlgLocRetry.dismiss();
            }
        });
        builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dlgLocRetry.dismiss();
                if (isNoPermission) {
                    Uri packageURI = Uri.parse("package:" + getPackageName());
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                    startActivity(intent);
                }
            }
        });

        dlgLocRetry = builder.setCancelable(false).create();
        dlgLocRetry.show();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isSupportTouchBack = false;
        setContentView(R.layout.activity_main);

        if (JPushInterface.isPushStopped(getApplicationContext())) {
            JPushInterface.resumePush(getApplicationContext());
        }

        layTitle = (TitleLayout) findViewById(R.id.lay_title);

        layPager = (PagerLayout) findViewById(R.id.lay_pager);
        layPager.pushNewContent(layMain = new MainLayout(this), false);

        ImageView menu = (ImageView) LayoutInflater.from(layMain.getContext()).inflate(R.layout.layout_title_menu_image, null);
        menu.setImageResource(R.drawable.square_selector_filter);
        menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layMain.showSquareLayoutDialog();
            }
        });
        layTitle.pushContent(null, makeImageTitle(R.mipmap.logo_90), menu, false);

        layPager.setOnStateChangedListener(new PagerLayout.OnStateChangedListener() {
            @Override
            public void upToCurrent() {
                layTitle.returnToCurrentContent();
            }

            @Override
            public void backToLast() {
                layTitle.popToLastContent();
            }

            @Override
            public void touchMove(float progress) {
                layTitle.setToLastAnimationProgress(progress);
            }
        });

        layMain.setOnBottomTabClickListener(new MainLayout.OnBottomTabClickListener() {
            @Override
            public void onSquareClick(int menuId) {
                if (!validClickFrequency("bottom")) return;
                layMain.dealBottomMenuClick(menuId);

                ImageView menu = (ImageView) LayoutInflater.from(layMain.getContext()).inflate(R.layout.layout_title_menu_image, null);
                menu.setImageResource(R.drawable.square_selector_filter);
                menu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        layMain.showSquareLayoutDialog();
                    }
                });
                layTitle.pushContent(null, makeImageTitle(R.mipmap.logo_90), menu, false);
            }

            @Override
            public void onDateClick(int menuId) {
                Once.getInstance().coverMainDateMenu(MainActivity.this, layOnce);

                if (!validClickFrequency("bottom")) return;
                layMain.dealBottomMenuClick(menuId);

                TextView menu = (TextView) LayoutInflater.from(layMain.getContext()).inflate(R.layout.layout_title_menu_text, null);
                menu.setText(R.string.main_profile_date);
                menu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_date), null, true);
                        layPager.pushNewContent(layMainProfileDate = new MainProfileDateLayout(MainActivity.this), true);
                    }
                });
                layTitle.pushContent(null, getString(R.string.main_profile), menu, false);
            }

            @Override
            public void onCenterClick(int menuId) {
                if (!validClickFrequency("bottom")) return;

                Intent intent = new Intent(MainActivity.this, DateStartActivity.class);
                startActivity(intent);
            }

            @Override
            public void onMessageClick(int menuId) {
                if (!validClickFrequency("bottom")) return;
                layMain.dealBottomMenuClick(menuId);

                layTitle.pushContent(null, getString(R.string.main_message), null, false);
            }

            @Override
            public void onProfileClick(int menuId) {
                if (!validClickFrequency("bottom")) return;
                layMain.dealBottomMenuClick(menuId);

                ImageView menu = (ImageView) LayoutInflater.from(layMain.getContext()).inflate(R.layout.layout_title_menu_image, null);
                menu.setImageResource(R.mipmap.profile_edit);
                menu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!validClickFrequency("profile")) return;
                        Intent intent = new Intent(MainActivity.this, ProfileInfoEditActivity.class);
                        startActivity(intent);
                    }
                });

                layTitle.pushContent(null, getString(R.string.main_profile), menu, false);
            }
        });

        layMain.setOnProfileMenuClickListener(new MainProfileLayout.OnProfileMenuClickListener() {
            @Override
            public void onEditClick() {
                if (!validClickFrequency("profile")) return;

                Intent intent = new Intent(MainActivity.this, ProfileInfoEditActivity.class);
                startActivity(intent);
            }

            @Override
            public void onAlbumClick() {
                if (!validClickFrequency("profile")) return;

                Intent intent = new Intent(MainActivity.this, ProfileAlbumEditActivity.class);
                startActivity(intent);
            }

            @Override
            public void onDateClick() {
                if (!validClickFrequency("profile")) return;

                layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_date), null, true);
                layPager.pushNewContent(layMainProfileDate = new MainProfileDateLayout(MainActivity.this), true);
            }

            public void onConcernClick() {
                if (!validClickFrequency("profile")) return;

                layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_concern), null, true);
                final MainProfileConcernLayout layMainProfileConcern = new MainProfileConcernLayout(MainActivity.this);
                layPager.pushNewContent(layMainProfileConcern, true);
            }

            @Override
            public void onBalanceClick() {
                if (!validClickFrequency("profile")) return;

                layMainProfileBalance = new MainProfileBalanceLayout(MainActivity.this);

                TextView menu = (TextView) LayoutInflater.from(layMain.getContext()).inflate(R.layout.layout_title_menu_text, null);
                menu.setText(R.string.balance_charge);
                menu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MainProfileBalanceChargeLayout layMainProfileDateCharge = new MainProfileBalanceChargeLayout(MainActivity.this);
                        layTitle.pushNewContent(makeBackView(), getString(R.string.balance_charge), null, true);
                        layPager.pushNewContent(layMainProfileDateCharge, true);
                    }
                });
                layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_balance), menu, true);
                layPager.pushNewContent(layMainProfileBalance, true);
            }

            @Override
            public void onFansClick() {
                if (!validClickFrequency("profile")) return;

                layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_fans), null, true);
                final MainProfileFansLayout layMainProfileFans = new MainProfileFansLayout(MainActivity.this);
                layPager.pushNewContent(layMainProfileFans, true);
            }

            @Override
            public void onAuthClick() {
                if (!validClickFrequency("profile")) return;

                layMainProfileAuth = new MainProfileAuthLayout(MainActivity.this);
                layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_auth), null, true);
                layPager.pushNewContent(layMainProfileAuth, true);
            }

            @Override
            public void onSysSettingsClick() {
                if (!validClickFrequency("profile")) return;

                layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_sys_set), null, true);
                layPager.pushNewContent(new MainProfileSettingsLayout(MainActivity.this), true);
            }
        });

        layOnce = (ViewGroup) findViewById(R.id.lay_once);
        Once.getInstance().coverMainMakeDate(this, layOnce);

        requestTokenUp();
    }

    private void requestTokenUp() {
        String platform = "paishen";
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(),
                    PackageManager.GET_META_DATA);
            platform = appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (PackageManager.NameNotFoundException ignored) {
        }

        PnwHttpManager.Token.up(TAG, BaseUtil.getAppVersionCode(), platform, new PnwOkCallbackAdapter<HttpRespData<UpgradeInfo>>() {
            @Override
            public void onResponse(HttpRespData<UpgradeInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == PnwHttpManager.Token.UPGRADE) {
                    showUpgradeDialog(response.errmsg, response.data.description, response.data.url, response.data.compat);
                } else if (response.errcode != C.http.RESULT_SUCCESS) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                //
            }
        });
    }

    private void showUpgradeDialog(String title, String message, final String downUrl, final boolean canCancel) {
        View menu = LayoutInflater.from(this).inflate(R.layout.dialog_upgrade, null);
        final ViewGroup layContent = (ViewGroup) menu.findViewById(R.id.lay_content);
        txUpgrade = (TextView) menu.findViewById(R.id.tx_upgrade);
        pbUpgrade = (ProgressBar) menu.findViewById(R.id.pb_upgrade);
        pbUpgrade.setAlpha(0);
        TextView txTitle = (TextView) menu.findViewById(R.id.tx_title);
        txTitle.setText(title);
        final TextView txMessage = (TextView) menu.findViewById(R.id.tx_message);
        txMessage.setMovementMethod(ScrollingMovementMethod.getInstance());
        txMessage.setText(Html.fromHtml(message));
        View viewCancel = menu.findViewById(R.id.tx_cancel);
        if (canCancel) {
            viewCancel.setVisibility(View.VISIBLE);
            viewCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dlgUpgrade.dismiss();
                }
            });
        }
        final TextView viewSubmit = (TextView) menu.findViewById(R.id.tx_confirm);
        txInstall = viewSubmit;
        viewSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (canCancel) dlgUpgrade.dismiss();
                if (!TextUtils.isEmpty(downUrl)) {
                    UpgradeService.launch(MainActivity.this, downUrl);
                    viewSubmit.setEnabled(false);
                    viewSubmit.setText(R.string.upgrade_ing);
                    layContent.removeView(txMessage);
                    pbUpgrade.animate().alpha(1).setDuration(400).start();
                }
            }
        });

        dlgUpgrade = new AlertDialog.Builder(this).setCancelable(canCancel).setView(menu).create();
        dlgUpgrade.show();
    }

    /**
     * 检验点击频率，避免一起按
     */
    private boolean validClickFrequency(final String flag) {
        switch (flag) {
            case "profile": {
                long currClickTimestamp = System.currentTimeMillis();
                if (currClickTimestamp - clickBottomTimestamp < 500) {
                    return false;
                } else {
                    clickProfileTimestamp = currClickTimestamp;
                    return true;
                }
            }
            case "bottom": {
                long currClickTimestamp = System.currentTimeMillis();
                if (currClickTimestamp - clickProfileTimestamp < 500) {
                    return false;
                } else {
                    clickBottomTimestamp = currClickTimestamp;
                    return true;
                }
            }
            default:
                return true;
        }
    }


    @Override
    public void onBackPressed() {
        if (layPager.isDoingAnim()) {
            return;
        }

        if (!layPager.isOnlyOnePageOrEmpty()) {
            layPager.popToLastContent();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onEventMainThread(BusEvent event) {
        super.onEventMainThread(event);
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                // 应约列表跳转
                case BusEvent.ACTION_TO_MAIN_PROFILE_AUTH:
                    layMainProfileAuth = new MainProfileAuthLayout(MainActivity.this);
                    layTitle.pushNewContent(makeBackView(), getString(R.string.main_profile_auth), null, true);
                    layPager.pushNewContent(layMainProfileAuth, true);
                    break;
                // 真人认证选择头像
                case BusEvent.ACTION_PICTURE_QUERY_OUT:
                    if (layMainProfileAuth != null)
                        layMainProfileAuth.setUserAvatar(String.valueOf(event.content));
                    break;

                // 下载新版本进度更新
                case BusEvent.ACTION_UPGRADE_DOWNLOAD_PROGRESS:
                    UpgradeService.FileInfo f = (UpgradeService.FileInfo) event.content;
                    if (pbUpgrade != null) pbUpgrade.setProgress(f.progress);
                    if (txUpgrade != null) txUpgrade.setText(f.getCurrDescription());
                    break;
                // 下载新版本完成 打开更新按钮
                case BusEvent.ACTION_UPGRADE_DOWNLOAD_FINISH:
                    if (txInstall != null) {
                        txInstall.setEnabled(true);
                        txInstall.setText(R.string.frame_upgrade_install);
                        txInstall.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                UpgradeService.installApk(MainActivity.this);
                            }
                        });
                    }
                    break;
                case BusEvent.ACTION_REFRESH_MAIN_MESSAGE_CLEAR_READ:
                case BusEvent.ACTION_REFRESH_MAIN_MESSAGE_NEW_MESSAGE:
                case BusEvent.ACTION_REFRESH_MAIN_MESSAGE_RESET_NICK:
                    layMain.initProfileMessage();
                    break;
                // 充值
                case BusEvent.ACTION_REFRESH_BALANCE_BY_CHARGE:
                    if (layMainProfileBalance != null) layMainProfileBalance.initWallet();
                    break;
                // 更新我的约会信息
//                case BusEvent.ACTION_MAIN_PROFILE_DATE_CONFIRM_CANCEL:
//                case BusEvent.ACTION_MAIN_PROFILE_DATE_COMMENT_FINISH:
                case BusEvent.ACTION_REFRESH_MAIN_PROFILE_DATE:
                    if (layMainProfileDate != null) layMainProfileDate.refresh();
                    break;
                // 更新我的认证信息 来自推送 请求网络
                case BusEvent.ACTION_REFRESH_MAIN_PROFILE_AUTH:
                    layMain.initProfileInfo(true);
                    break;
                // 更新我的认证信息 提交审核
                case BusEvent.ACTION_MAIN_PROFILE_AUTH_SUBMIT:
                    layMain.initProfileInfo(false);
                    onBackPressed(); // 由审核界面退到主界面来
                    break;
                // 支付完成刷新余额
                case BusEvent.ACTION_REFRESH_DATE_INFO_STATUS_PAY_SUCCESS:
                case BusEvent.ACTION_REFRESH_MAIN_PROFILE:
                    layMain.initProfileInfo(false);
                    break;
                case BusEvent.ACTION_REFRESH_MAIN_PROFILE_ALBUM:
                    layMain.initProfileAlbumPreview();
                    break;
                // 新的约会
                case BusEvent.ACTION_REFRESH_MAIN_DATE_NEW_DATE:
                    layMain.refreshDate(true);
                    break;
                case BusEvent.ACTION_REFRESH_MAIN_DATE_EMPTY:
                    layMain.refreshDate(false);
                    break;
            }
        }
    }


}
